// pages/index/index.ts
import { Course, AppSettings, LessonTime } from '@/typings';
import { showToast, showConfirmDialog, getWeekdayString, calculateCurrentWeek, formatDateToYYYYMMDD, getShortWeekdayString, getWeekDates } from '../../../../../utils/base';

// 初始模拟数据 (实际项目中应从后端或云数据库获取)
const initialCourses: Course[] = [
  { id: 'c1', weekday: 6, lessonIndex: 1, weekType: 'every', courseName: 'ART222产品设计工作坊—产品设计材料、色彩与表面工艺', teacher: '张萌', room: '4A-213', status: 'enable', color: 'orange' },
  { id: 'c2', weekday: 6, lessonIndex: 2, weekType: 'every', courseName: '大学生创业基础', teacher: '张萌', room: '4A-213', status: 'enable', color: 'blue' },
  { id: 'c3', weekday: 6, lessonIndex: 3, weekType: 'every', courseName: '大学生创业基础', teacher: '张萌', room: '4A-213', status: 'enable', color: 'green' },
  { id: 'c4', weekday: 6, lessonIndex: 4, weekType: 'every', courseName: 'ART222产品设计工作坊—产品设计材料、色彩与表面工艺', teacher: '张萌', room: '4A-213', status: 'enable', color: 'orange' },
  { id: 'c5', weekday: 1, lessonIndex: 3, weekType: 'every', courseName: '高级算法与数据结构', teacher: '李教授', room: '教A-301', status: 'enable', color: 'blue' },
  { id: 'c6', weekday: 2, lessonIndex: 5, weekType: 'single', courseName: '数据挖掘与机器学习', teacher: '王老师', room: '实验楼B-205', status: 'enable', color: 'green', remark: '单周课程' },
  { id: 'c7', weekday: 2, lessonIndex: 5, weekType: 'double', courseName: '人工智能导论', teacher: '赵老师', room: '实验楼B-205', status: 'enable', color: 'orange', remark: '双周课程' },
  { id: 'c8', weekday: 3, lessonIndex: 1, weekType: 'every', courseName: '微积分A', teacher: '陈老师', room: '教B-101', status: 'disable', color: 'blue', remark: '停课' },
];

// 默认设置 (与 settings 页面保持一致)
const DEFAULT_SETTINGS: AppSettings = {
  totalWeeks: 18,
  startDate: formatDateToYYYYMMDD(new Date()), // 默认今天
  lessonTimes: [
    { index: 1, startTime: '08:00', endTime: '08:45' },
    { index: 2, startTime: '08:50', endTime: '09:35' },
    { index: 3, startTime: '09:50', endTime: '10:35' },
    { index: 4, startTime: '10:40', endTime: '11:25' },
    { index: 5, startTime: '11:30', endTime: '12:15' },
    { index: 6, startTime: '14:00', endTime: '14:45' },
    { index: 7, startTime: '14:50', endTime: '15:35' },
    { index: 8, startTime: '15:50', endTime: '16:35' },
    { index: 9, startTime: '16:40', endTime: '17:25' },
    { index: 10, startTime: '18:30', endTime: '19:15' },
    { index: 11, startTime: '19:20', endTime: '20:05' },
    { index: 12, startTime: '20:10', endTime: '20:55' },
  ].sort((a, b) => a.index - b.index),
};

// 增强的课程数据，用于显示
interface EnhancedCourse extends Course {
  displayStartTime: string; // 从LessonTime匹配到的开始时间
  displayEndTime: string;   // 从LessonTime匹配到的结束时间
}

// 增强的课程数据，用于在表格单元格中显示
interface CourseDisplayCell {
  course: Course;
  startTime: string; // 从AppSettings中匹配到的时间
  endTime: string;   // 从AppSettings中匹配到的时间
  color?: 'orange' | 'blue' | 'green';
  status: 'enable' | 'disable';
  weekType: 'every' | 'single' | 'double';
  courseName: string;
  teacher?: string;
  room?: string;
  id: string; // 方便传递给事件
}

// 表格行数据结构
interface LessonRow {
  lessonTime: LessonTime;
  coursesByWeekday: CourseDisplayCell[][]; // [ [], [], [], [], [], [], [] ] 星期日到星期六的课程数组
}

Page({
  data: {
    currentDate: '', // 例如 "2024年5月18日"
    currentWeekday: '', // 例如 "周六"
    currentWeek: 0, // 当前第几周
    isSingleWeek: null as boolean | null, // 当前周是否为单周
    allCourses: [] as Course[], // 所有课程数据
    todayCourses: [] as EnhancedCourse[], // 今日课程数据（增强型）
    appSettings: DEFAULT_SETTINGS, // 应用设置
    showFullSchedulePopup: false, // 控制完整课表弹窗显示

    // 以下是 fullSchedulePopup 整合后的数据
    sortedLessons: [] as LessonRow[], // 最终用于WXML渲染的表格数据
    weekDates: [] as { weekday: string; monthDay: string; index: number }[], // 本周的日期信息
    currentDayOfWeek: -1, // 今天是星期几 (0-6)
    isSettingsValid: false, // 标记设置是否完整有效

    showActionSheet: false,
    actions: [
      { name: '编辑课程', value: 'edit' },
      { name: '删除课程', value: 'delete', color: '#ee0a24' }
    ],
    selectedCourseId: '', // 存储当前长按的课程ID
  },

  onLoad() {
    this.initPageData();
  },

  onShow() {
    // 页面显示时刷新课程和设置数据
    this.loadSettings();
    this.loadCourses();
    // 如果弹窗已经打开，重新加载数据
    if (this.data.showFullSchedulePopup) {
      this.loadFullScheduleData();
    }
  },

  /**
   * 初始化页面日期信息和加载设置
   */
  initPageData() {
    const date = new Date();
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const weekday = date.getDay(); // 0-6，星期日-星期六

    this.setData({
      currentDate: `${year}年${month}月${day}日`,
      currentWeekday: getWeekdayString(weekday),
    });

    this.loadSettings();
    this.loadCourses();
  },

  /**
   * 从本地存储加载应用设置
   */
  loadSettings() {
    try {
      const storedSettingsStr = wx.getStorageSync('appSettings');
      let settings: AppSettings = storedSettingsStr ? JSON.parse(storedSettingsStr) : DEFAULT_SETTINGS;
      settings.lessonTimes.sort((a, b) => a.index - b.index);

      if (!storedSettingsStr) {
        wx.setStorageSync('appSettings', JSON.stringify(DEFAULT_SETTINGS));
      }

      this.setData({
        appSettings: settings,
      });

      if (settings.startDate) {
        const currentWeek = calculateCurrentWeek(settings.startDate);
        const isSingleWeek = currentWeek % 2 !== 0;
        this.setData({
          currentWeek,
          isSingleWeek,
        });
      } else {
        this.setData({
          currentWeek: 0,
          isSingleWeek: null,
        });
      }
    } catch (e) {
      console.error('加载应用设置失败', e);
      showToast('加载设置失败，使用默认设置');
      this.setData({ appSettings: DEFAULT_SETTINGS });
    }
  },

  /**
   * 从本地存储加载课程数据，并过滤出今日课程
   */
  loadCourses() {
    wx.showLoading({ title: '加载课程中...', mask: true });
    try {
      const storedCoursesStr = wx.getStorageSync('courseList');
      let courses: Course[] = storedCoursesStr ? JSON.parse(storedCoursesStr) : [];

      if (courses.length === 0) {
        courses = initialCourses;
        wx.setStorageSync('courseList', JSON.stringify(initialCourses));
      }

      this.setData({
        allCourses: courses
      });
      this.filterTodayCourses();
    } catch (e) {
      console.error('加载课程数据失败', e);
      showToast('加载课程失败，请稍后重试');
      this.setData({
        allCourses: initialCourses
      });
      this.filterTodayCourses();
    } finally {
      wx.hideLoading();
    }
  },

  /**
   * 过滤出当前日期的课程，并结合单双周、节次时间进行处理
   */
  filterTodayCourses() {
    const today = new Date().getDay();
    const { currentWeek, isSingleWeek, appSettings } = this.data;
    const lessonTimesMap = new Map<number, LessonTime>();
    appSettings.lessonTimes.forEach(lt => lessonTimesMap.set(lt.index, lt));

    const todayCourses: EnhancedCourse[] = [];
    this.data.allCourses.forEach(course => {
      if (course.weekday === today) {
        const weekTypeMatches = course.weekType === 'every' ||
          (course.weekType === 'single' && isSingleWeek) ||
          (course.weekType === 'double' && !isSingleWeek);

        if (weekTypeMatches && currentWeek > 0 && currentWeek <= appSettings.totalWeeks) {
          const lessonTime = lessonTimesMap.get(course.lessonIndex);
          if (lessonTime) {
            todayCourses.push({
              ...course,
              displayStartTime: lessonTime.startTime,
              displayEndTime: lessonTime.endTime,
            });
          }
        }
      }
    });

    todayCourses.sort((a, b) => a.lessonIndex - b.lessonIndex);

    this.setData({
      todayCourses
    });
  },

  /**
   * 跳转到添加课程页面
   */
  navigateToAddCourse() {
    wx.navigateTo({
      url: './add/index',
      events: {
        courseUpdated: () => {
          this.loadCourses();
        }
      }
    });
  },

  /**
   * 跳转到设置页面
   */
  navigateToSettings() {
    wx.navigateTo({
      url: './setting/index',
      events: {
        settingsUpdated: () => {
          this.loadSettings();
          this.loadCourses();
        }
      }
    });
  },

  /**
   * 显示整个课表弹窗，并加载数据
   */
  showFullSchedule() {
    this.setData({
      showFullSchedulePopup: true
    });
    this.loadFullScheduleData();
  },

  /**
   * 关闭整个课表弹窗的回调
   */
  onFullSchedulePopupClose() {
    this.setData({
      showFullSchedulePopup: false
    });
  },

  /**
   * 加载完整课表数据
   */
  loadFullScheduleData() {
    wx.showLoading({ title: '加载课表中...', mask: true });
    try {
      const storedSettingsStr = wx.getStorageSync('appSettings');
      let appSettings: AppSettings | null = storedSettingsStr ? JSON.parse(storedSettingsStr) : null;

      const isSettingsValid = !!appSettings &&
        !!appSettings.lessonTimes &&
        appSettings.lessonTimes.length > 0 &&
        !!appSettings.totalWeeks &&
        appSettings.totalWeeks > 0 &&
        !!appSettings.startDate;

      this.setData({ isSettingsValid });

      if (!isSettingsValid) {
        this.setData({
          appSettings: {} as AppSettings,
          sortedLessons: [],
          weekDates: [],
        });
        return;
      }

      (appSettings as AppSettings).lessonTimes.sort((a, b) => a.index - b.index);

      const today = new Date();
      const currentDayOfWeek = today.getDay();
      const weekDatesRaw = getWeekDates((appSettings as AppSettings).startDate, this.data.currentWeek);

      const weekDates = weekDatesRaw.map((date, index) => ({
        weekday: getShortWeekdayString(date),
        monthDay: `${date.getMonth() + 1}/${date.getDate()}`,
        index: index,
      }));

      this.setData({
        appSettings: appSettings as AppSettings,
        weekDates,
        currentDayOfWeek,
      });

      this.populateScheduleGrid();
    } catch (e) {
      console.error('加载完整课表数据失败', e);
    } finally {
      wx.hideLoading();
    }
  },

  /**
   * 填充表格数据
   */
  populateScheduleGrid() {
    const { appSettings, allCourses, currentWeek, isSingleWeek } = this.data;
    if (!appSettings || !appSettings.lessonTimes || appSettings.lessonTimes.length === 0) {
      this.setData({ sortedLessons: [] });
      return;
    }

    const lessonTimes = appSettings.lessonTimes;
    const lessonTimesMap = new Map<number, LessonTime>();
    lessonTimes.forEach(lt => lessonTimesMap.set(lt.index, lt));

    const sortedLessons: LessonRow[] = lessonTimes.map(lt => ({
      lessonTime: lt,
      coursesByWeekday: Array.from({ length: 7 }, () => []),
    }));

    allCourses.forEach(course => {
      if (currentWeek <= 0 || currentWeek > appSettings.totalWeeks) {
        return;
      }

      const weekTypeMatches = course.weekType === 'every' ||
        (course.weekType === 'single' && isSingleWeek) ||
        (course.weekType === 'double' && !isSingleWeek);

      if (weekTypeMatches) {
        const lessonRowIndex = sortedLessons.findIndex(row => row.lessonTime.index === course.lessonIndex);
        if (lessonRowIndex !== -1 && course.weekday >= 0 && course.weekday <= 6) {
          const lt = lessonTimesMap.get(course.lessonIndex);
          if (lt) {
            const displayCell: CourseDisplayCell = {
              course: course,
              startTime: lt.startTime,
              endTime: lt.endTime,
              color: course.color,
              status: course.status,
              weekType: course.weekType,
              courseName: course.courseName,
              teacher: course.teacher,
              room: course.room,
              id: course.id,
            };
            sortedLessons[lessonRowIndex].coursesByWeekday[course.weekday].push(displayCell);
          }
        }
      }
    });

    this.setData({
      sortedLessons
    });
  },

  /**
   * 长按课程卡片，显示操作菜单
   * @param e 事件对象
   */
  onLongPressCourse(e: WechatMiniprogram.CustomEvent) {
    const { courseId } = e.currentTarget.dataset;
    this.setData({
      selectedCourseId: courseId,
      showActionSheet: true,
    });
  },

  /**
   * 操作菜单选择事件
   * @param e 事件对象
   */
  async onActionSheetSelect(e: WechatMiniprogram.CustomEvent) {
    const { value } = e.detail;
    const courseId = this.data.selectedCourseId;
    if (!courseId) return;

    this.setData({ showActionSheet: false });

    if (value === 'edit') {
      wx.navigateTo({
        url: `/pages/addCourse/addCourse?id=${courseId}`,
        events: {
          courseUpdated: () => {
            this.loadCourses();
            this.loadFullScheduleData();
          }
        }
      });
    } else if (value === 'delete') {
      const confirm = await showConfirmDialog('删除课程', '确认删除此课程吗？');
      if (confirm) {
        wx.showLoading({ title: '删除中...', mask: true });
        try {
          let updatedCourses = this.data.allCourses.filter(course => course.id !== courseId);
          wx.setStorageSync('courseList', JSON.stringify(updatedCourses));
          this.setData({
            allCourses: updatedCourses
          });
          this.loadCourses();
          this.loadFullScheduleData();
          showToast('课程删除成功');
        } catch (error) {
          console.error('删除课程失败', error);
          showToast('删除失败，请重试');
        } finally {
          wx.hideLoading();
        }
      }
    }
  },

  /**
   * 关闭操作菜单
   */
  onActionSheetClose() {
    this.setData({
      showActionSheet: false,
      selectedCourseId: '',
    });
  },
});
